#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "mystdio.h"

// 实现申请文件资源
static MyFile* BuyFile(int fd, int flag) {
    MyFile* f = (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL) {
        return NULL;
    }
    f->fileno = fd;
    f->bufferlen = 0;
    f->flag = flag;
    f->flush_method = LINE_FLUSH;
    memset(f->buffer, 0, sizeof(f->buffer));
    return f;
}

// 打开文件
MyFile* MyOpen(const char* path, const char* mode) {
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w")) {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }else if(strcmp(mode, "r")) {
        flag = O_RDONLY;
        fd = open(path, flag);
    }else if(strcmp(mode, "a")) {
        flag = O_WRONLY | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }else {
        // to do 
    }
    if(fd < 0) return NULL;
    return BuyFile(fd, flag);
}

// 关闭文件
void MyClose(MyFile* file) {
    if(file->fileno < 0) return;
    MyFFlush(file);
    close(file->fileno);
    free(file);
}

// 向文件里面写入数据
int MyFwrite(MyFile *file, void *str, int len) {
    memcpy(file->buffer + file->bufferlen, str, len);
    file->bufferlen += len;
    if((file->flush_method & LINE_FLUSH) && file->buffer[file->bufferlen - 1] == '\n') {
        MyFFlush(file);
    }
    return 0;
}

// 刷新数据
void MyFFlush(MyFile *file) {
    if(file->bufferlen <= 0) return;
    int n = write(file->fileno, file->buffer, file->bufferlen);
    (void)n;
    fsync(file->fileno);
    file->bufferlen = 0;
}